<style lang="less">
@import "../../styles/common.less";
</style>

<template>
  <div class="margin-top-10">
      <Form :label-width="50" size="small" inline>
        <FormItem label="班级">
          <Input
            v-model.trim="queryForm.class_name"
            @on-enter="searchSchedule"
            placeholder="请输入班级名称" 
            style="width: 120px;margin-right:3px"
          ></Input>
        </FormItem>
        <FormItem label="项目">
          <Input
            v-model.trim="queryForm.class_type"
            @on-enter="searchSchedule"
            placeholder="请输入项目名称" 
            style="width: 120px;margin-right:3px"
          ></Input>
        </FormItem>
        <FormItem label="集团">
          <Input
            v-model.trim="queryForm.group_name"
            @on-enter="searchSchedule"
            placeholder="请输入集团名称" 
            style="width: 120px;margin-right:3px"
          ></Input>
        </FormItem>
        <FormItem label="上课校区" :label-width="60">
          <Input
            v-model.trim="queryForm.campus_name"
            @on-enter="searchSchedule"
            placeholder="请输入上课校区" 
            style="width: 120px;margin-right:3px"
          ></Input>
        </FormItem>
        <!-- <FormItem label="课表">
          <Input
            v-model.trim="queryForm.schedule_name"
            @on-enter="searchSchedule"
            placeholder="请输入课表名称" 
            style="width: 150px;margin-right:3px"
          ></Input>
        </FormItem> -->
        <!-- <FormItem label="课次">
          <Input
            v-model.trim="queryForm.class_time_name"
            @on-enter="searchSchedule"
            placeholder="请输入课次名称" 
            style="width: 150px;margin-right:3px"
          ></Input>
        </FormItem> -->
        <FormItem :label-width="80" label="上课时间">
          <TimePicker v-model="class_time_range" confirm format="HH:mm" type="timerange" placement="bottom-end" placeholder="请选择时间段" style="width: 168px"></TimePicker>
        </FormItem>
        <FormItem>
          <Button @click="searchSchedule" type="primary">查询</Button>
        </FormItem>
      </Form>
    <div>
        <Button @click="uploadModal=true" type="primary">导入课表</Button>
    </div>
    <div class="margin-top-10">
      <Table :columns="scheduleColumn" :data="scheduleData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalSchedule"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getSchedule"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalSchedule}}条</Page>
    </Row>

    <Modal v-model="uploadModal" @on-cancel="hideUploadModal">
      <div slot="header">
        <p>
          导入表格
          <span style="font-weight: 100;font-size: 12px;margin-left: 5px">
            (请严格按照
            <a :href="excelFile" download="模板.xlsx">模板</a>格式上传表格)
          </span>
        </p>
      </div>
      <HorizonUploader ref="uploader"></HorizonUploader>
      <div slot="footer">
        <Button type="primary" @click="handleUpload">上传</Button>
      </div>
    </Modal>

    <!-- 查看学生 -->
    <Modal
        v-model="studentModal"
        title="学生情况">
        <Table :columns="studentColumn" :data="studentTableData"></Table>
    </Modal>

    <!-- 绑定教室 -->
    <Modal
        v-model="bindClassroomModal"
        title="选择教室">
        <RadioGroup v-model="bindClassroomId">
          <Radio v-for="item in classroomList" :key="item._id" :label="item._id">
              <span>{{item.group_name?item.group_name+'-':''}}{{item.campus_name?item.campus_name+'-':''}}{{item.name}}({{item.num}})</span>
          </Radio>
      </RadioGroup>
      <div slot="footer">
        <Button type="primary" @click="bindClassroom">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
    importSchedule,
    deleteSchedule,
    getSchedule,
    bindClassroom
} from '../../controllers/scheduleStat';
import {
  getClassroom
} from '../../controllers/classroom';
import Uploader from "../../views/weiget/uploader.vue";
import ImageUtils from "@/libs/image.js";
import HorizonUploader from "./components/HorizonUploader.vue";
import moment from 'moment';
import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";
import _ from "lodash";
import DateUtils from "../../../node_modules/iview/src/utils/date";
import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";
import iconBind from "../../images/bind.png";

import excelFile from "../../assets/scheduleExcel.xlsx";

export default {
  components: {
    Uploader,
    HorizonUploader,
    Tooltip,
    Btn
  },
  data() {
    return {
      tableLoading: true,
      queryForm:{
        class_name:'',
        group_name:'',
        campus_name:'',
        class_type:'',
        schedule_name:'',
        class_time_name:'',
        class_start_time:'',
        class_end_time:''
      },
      class_time_range: '',
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalSchedule: 0,
      scheduleColumn: [
        // {
        //   title: "学校",
        //   align: "center",
        //   key: "school_name",
        //   width: 200
        // },
        {
          title: "班级编号",
          align: "center",
          key: "class_num",
          width: 200
        },
        {
          title: "班级名称",
          align: "center",
          key: "class_name",
          width: 160
        },
        {
          title: "项目",
          align: "center",
          key: "class_type",
          width: 160
        },
        // {
        //   title: "课表编号",
        //   align: "center",
        //   key: "schedule_num",
        //   width: 160
        // },
        // {
        //   title: "课表名称",
        //   align: "center",
        //   key: "schedule_name",
        //   width: 160
        // },
        // {
        //   title: "课次编号",
        //   align: "center",
        //   key: "class_time_num",
        //   width: 160
        // },
        // {
        //   title: "课次名称",
        //   align: "center",
        //   key: "class_time_name",
        //   width: 160
        // },
        {
          title: "集团",
          align: "center",
          key: "group_name",
          width: 160
        },
        {
          title: "上课校区",
          align: "center",
          key: "campus_name",
          width: 160
        },
        {
          title: "教室编号",
          align: "center",
          key: "classroom_num",
          width: 160
        },
        {
          title: "教室名称",
          align: "center",
          key: "classroom_name",
          width: 160
        },
        {
          title: "上课日期",
          align: "center",
          width: 200,
          render: (h,{row}) => {
            const formatStartDate= moment(row['class_start_date']).format('YYYY-MM-DD')
            const formatEndDate = moment(row['class_end_date']).format('YYYY-MM-DD')
            return (
              <span>{formatStartDate}~{formatEndDate}</span>
            )
          }
        },
        {
          title: "上课时间段",
          align: "center",
          width: 300,
          render: (h,{row}) => {
            return (

              <span>
                <span style="margin-right:6px;">{this.formatDay(row.on_class_day)}</span>
                {row['class_start_time']}~{row['class_end_time']}
              </span>
            )
          }
        },
        {
          title: "应上课人数",
          align: "center",
          width: 200,
          render: (h,{row}) => {
            const len = row['student_collection']&&row['student_collection'].length || 0
            return (
              <i-button type="text" onClick={()=>{this.previewStudent(row)}}>{len}</i-button>
            )
          }
        },
        {
          title: "操作",
          align: "center",
          minWidth: 240,
          fixed: 'right',
          render: (h, { row, column, index }) => {
            const _id = row._id;
            const name = row.class_type;
            return (
              <div class="operation">
                {
                  /*
                  <Tooltip content="编辑" placement="bottom">
                    <Btn
                      style={{ background: `url( ${iconEdit})` }}
                      onClick={() => this.handleEditSchedule(row)}
                    />
                  </Tooltip>
                  */
                }
                <Tooltip content="选择教室" placement="left">
                  <Btn
                    style={{ background: `url( ${iconBind})` }}
                    onClick={() => this.handleBindClassroom(row)}
                  />
                </Tooltip>
                <Tooltip content="删除" placement="right">
                  <Btn
                    style={{ background: `url( ${iconDelete})` }}
                    onClick={() => this.handleDelSchedule(_id, name)}
                  />
                </Tooltip>
              </div>
            );
          }
        }
      ],
      scheduleData: [],


      classroomList:[],
      bindClassroomModal:false,
      bindClassroomId:'',
      scheduleId:'',

      scheduleInfo: {
        _id:'',
        user_name: "",
        user_sex: "",
        user_avatar: "",
        user_num: "",
        user_school: "",
        user_class: "",
        user_phone: "",
        user_email: "",
      },
      modalTitle: "编辑课表信息",
      scheduleInfoRules: {
          user_name: [
            { required: true, message: "姓名不可以为空", trigger: "blur" }
          ],
          user_num: [
              {required: true, message: "学号不可以为空", trigger: "blur"}
          ],
          user_sex: [
              {required: true, message: "请选择性别", trigger: "blur"}
          ],
          user_school: [],
          user_class: [],
          user_email: [
            { type: "email", message: "邮箱格式不正确", trigger: "blur" }
          ],
          user_phone: [
            {
              pattern: /^1\d{10}$/,
              message: "电话格式不正确",
              trigger: "blur"
            }
          ]
      },
      departmentList: [],
      uploadModal: false,
      excelFile: excelFile,

      studentModal:false,
      studentTableData:[],
      studentColumn:[
        {
          title:'学号',
          key:'student_num',
          align:'center'
        },
        {
          title:'姓名',
          key:'student_name',
          align:'center'
        }
      ]
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    },
  },
  created() {
    this.loadScheduleData();
    this.loadClassroomData();
  },
  methods: {
    formatDay(days){
      const dayObj = {
        0:'周天',
        1:'周一',
        2:'周二',
        3:'周三',
        4:'周四',
        5:'周五',
        6:'周六',
      }
      if(!days||days.length===0){
        return ''
      }
      const strAry = []
      for(let key of days){
        strAry.push(dayObj[key])
      }
      return strAry.join(';')
    },
    getSchedule(page) {
      //获取分页参数，请求后端数据
      this.currentPage = page;
      this.tableLoading = true;
      this.loadScheduleData();
    },
    loadClassroomData(){
      // 筛选出已绑定设备的教室
      getClassroom({
        page_num:1,
        page_size:1000
      }).then(res=>{
        this.classroomList = (res.data.result||[]).filter(item=>item.related_devices&&item.related_devices.length)
      })
    },
    handleDelSchedule(id, name) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除科目【" + name + "】的课表？",
        onOk: () => {
          deleteSchedule({ _id: [id] }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.getSchedule(this.currentPage);
            }
          });
        }
      });
    },
    handleEditSchedule(row) {
      this.modalTitle = "编辑课程信息";
    },
    handleBindClassroom(row) {
      this.scheduleId = row._id;
      this.bindClassroomId = row.classroom_id;
      this.bindClassroomModal = true;
    },
    bindClassroom(){
      if(!this.bindClassroomId){
        return this.$Message.warning('请选择上课教室')
      }
      this.bindClassroomModal = false;
      this.tableLoading = true;
      bindClassroom({
        schedule_id:this.scheduleId,
        classroom_id:this.bindClassroomId
      }).then(res=>{
        this.tableLoading = false;
        if(res.code===0){
          this.$Message.success('设置成功')
          this.loadScheduleData();
        }
      }).catch(err=>{
        console.log(err)
        this.tableLoading = false;
      })
    },
    searchSchedule() {
      //to-do:检验关键词
      if(this.class_time_range&&this.class_time_range[0]&&this.class_time_range[1]){
        this.queryForm.class_start_time = this.class_time_range[0].replace(':','')
        this.queryForm.class_end_time = this.class_time_range[1].replace(':','')
      }else{
        this.queryForm.class_start_time = ''
        this.queryForm.class_end_time = ''
      }
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadScheduleData();
    },
    loadScheduleData() {
      getSchedule({
        page_num:this.currentPage, 
        page_size:this.pageSize,
        ...this.queryForm
      })
        .then(json => {
          let { total, data } = transscheduleData(json);
          this.totalSchedule = total;
          this.scheduleData = data;
          this.tableLoading = false;
          let tmp = _.map(data, item => item.uid);
          return tmp;
        })
    },
    resetForm() {
    },
    handleUpload() {
      if (!this.$refs["uploader"].hasFile) {
        this.$Message.error("请先选择文件");
        return;
      }
      var formData = new FormData();
      formData.append("file", this.$refs["uploader"].file);
      importSchedule(formData).then(json => {
        if (json.code == 0) {
          this.$Message.success(json.msg);
          this.hideUploadModal();
          this.getSchedule(this.currentPage);
        }
      });
    },
    hideUploadModal() {
      this.$refs["uploader"].reset();
      this.uploadModal = false;
    },
    previewStudent(row){
      const students = row.student_collection
      this.studentModal = true;
      this.studentTableData = students;
    }
  }
};

function transscheduleData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {} };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }

  let { total, result } = data;
  // }));
  return {
    total,
    data: result
  };
}

</script>